package toy.keli.edic.ui.home.homescreen

import android.annotation.SuppressLint
import androidx.collection.arraySetOf
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.data.local.entity.CategoryEntity
import toy.keli.edic.data.model.Book
import toy.keli.edic.data.model.Category
import toy.keli.edic.domain.model.WordModel
import toy.keli.edic.ui.bookmark.BookMarkEvent
import toy.keli.edic.ui.history.HistoryViewModel
import toy.keli.edic.ui.history.HistoryWords
import toy.keli.edic.ui.history.components.HistroyFilter
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.nowChapters
import toy.keli.edic.ui.home.wGroups
import toy.keli.edic.ui.level.LevelViewModel
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.components.FlowRow
import toy.keli.edic.ui.main.components.InputDialog
import toy.keli.edic.ui.main.components.ViewButton
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.view.MPopMenu

@SuppressLint("StateFlowValueCalledInComposition")
@Composable
@Preview(showBackground = true)
fun GroupInfoPage(ap: MutableState<Float>?=null){
    var cModel:Category
    if( LocalInspectionMode.current) {
        ActivityRun.context = LocalContext.current
        BookConf.setDefBook()
        BookConf.instance.initByData("章节01\nabc,about,after,ago\n\n章节02\nbefor,but")
        wGroups.addAll(BookConf.chapters)
        BookConf.words = listOf(
            WordModel(null,"abc","0",0),
            WordModel(null,"about","0",0)
        )
        HistoryWords.apply{
            add(WordModel(null,"after","0",0))
            add(WordModel(null,"ago","0",0))
        }
        HistoryWords.menu()
        cModel = Category(CategoryEntity("目录01"))
    }else {
        cModel = Book.getCategoryModel()
    }
    val boxModifier = Modifier
    if(ap!=null) {
        boxModifier.alpha(ap.value)
    }
    val name = BookConf.instance.name
    val funs = listOf("edit")
    val diffSet = remember {
        arraySetOf<String>()
    }
    val inSet = remember {
        arraySetOf<String>()
    }
    Box{
        InputDialog.add("AddArticle","SaveToFile",{
            BookMarkEvent.onAdd(it, 0)
            ActivityRun.msg("Saved")
        })
        if(! LocalInspectionMode.current) {
            val historyViewModel: HistoryViewModel = hiltViewModel()
            HistroyFilter.add(
                historyViewModel, listOf(
                    HistroyFilter.types.type,
                    HistroyFilter.types.level
                )
            )
        }
    }
    val lState = rememberLazyListState()
    val last = lState.layoutInfo.visibleItemsInfo.lastOrNull()
    HomeEvents.status.openDrowUp = last!=null && lState.layoutInfo.viewportEndOffset >= last.offset + last.size

    LazyColumn (modifier= boxModifier
        .padding(30.dp)
        , state = lState
    ){
        items(1) {
            /*
               Title("功能")
               Row{
                   funs.forEach {
                       Text(it,Modifier.clickable { HomeEvents.GroupInfoPage.onFunsClick(it) })
                   }
               }
               Title("包含")
               Row{
                   Button(onClick = { HomeEvents.GroupInfoPage.onAddInSetClick() }) {
                       Text("+")
                   }
                   inSet.forEach{
                       Text(it,Modifier.clickable { HomeEvents.GroupInfoPage.onInSetItemClick() })
                   }
               }

               Title("排除")
               Row{
                   Button(onClick = { HomeEvents.GroupInfoPage.onAddDiffSetClick() }) {
                       Text("+")
                   }
                   diffSet.forEach{
                       Text(it,Modifier.clickable { HomeEvents.GroupInfoPage.onDiffSetItemClick() })
                   }
               }
       */
            //目录
            //Title(cModel.entity.name){
            //    val pid = Book.cid()
            //    NavScreen.BookmarkScreen.open("?pid=${pid}")
            //}
            //书本
            //FlowRow {
            //    val articles = cModel.articles().collectAsState()
            //    articles.value.forEach{
            //        Text(text = mt(it.simpleName), fontSize = 14.sp, modifier = Modifier
            //            .padding(10.dp)
            //            .clickable { HomeEvents.GroupInfoPage.onBookClick(it) }
            //        )
            //    }
            //}

            //书本
            Row {
                Title(name.replace(Regex("\\.\\w+$"), "")) {
                    val pid = Book.cid()
                    BookMarkEvent.bookId = BookConf.instance.id
//                    NavScreen.BookmarkScreen.open("?pid=${pid}")
                    HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.showCategory)

                }
                ViewButton("listenBook"){
                    HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.showArticle)
                }
            }
            if (wGroups.size > 0) {
                FlowRow {
                    wGroups.forEach {
                        val tColor =
                            if (it.equals(nowChapters)) Color.Red else MaterialTheme.colorScheme.primary
                        Text(text = mt(it), color = tColor, fontSize = 14.sp, modifier = Modifier
                            .padding(10.dp)
                            .clickable { HomeEvents.GroupInfoPage.onChapterClick(it) }
                        )
                    }
                }
            }


//            val nowStatus = GlobalVal.wordViewModel.wordState.collectAsState()
//            val nowModel = nowStatus.value.wordModel
//            val words = GlobalVal.wordViewModel.cacheSub()
            if(BookConf.words.size>0) {
                val menu = MPopMenu(listOf(
                    MPopMenu.dataClass("Copy"),
                    MPopMenu.dataClass("export"),
                    MPopMenu.dataClass("Save"),
                    MPopMenu.dataClass("SaveAll"),
                    MPopMenu.dataClass("过滤"),
//                    MPopMenu.dataClass("exportAndOpen"),
//                    MPopMenu.dataClass("exportAndJumpTo")
                )).upMtTitle()
                Row {
                    Title("WordList") {
                       HomeEvents.GroupInfoPage.onFunsClick(menu)
                    }
                    menu.add()
                    ViewButton("findGame"){
                        HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.findGame)
                    }
                    ViewButton("jdc_select"){
                        HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.jdc_select)
                    }
                    ViewButton("jdc_write"){
                        HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.jdc_write)
                    }

                }
            }
            FlowRow {
                BookConf.words.forEach {
//                val tColor = if(it.isStudyed)  Color.Red else MaterialTheme.colors.primary
                    val tColor = if (it.word.equals(BookConf.instance.word)) Color.Red else MaterialTheme.colorScheme.primary
                    Text(text = it.word, color = tColor,
                        fontSize = 14.sp,
                        modifier = Modifier
                            .padding(10.dp)
                            .clickable { HomeEvents.GroupInfoPage.onWordClick(it) }
                    )
                }
            }

            if(HistoryWords.size>1) {
                Title(mt("WordHistory"))
                FlowRow {
                    HistoryWords.menu.items.reversed().forEach {
                        Text(text = it.title,
                            fontSize = 14.sp,
                            modifier = Modifier
                                .padding(10.dp)
                                .clickable {
                                    HistoryWords.slice(it.index)
                                    HomeEvents.GroupInfoPage.onHistoryWordClick(it.value as WordModel)
                                }
                        )
                    }
                    HistoryWords.sliceDiscard.reversed().forEach {
                        Text(text = it.word, color = Color.Gray,
                            fontSize = 14.sp,
                            modifier = Modifier
                                .padding(10.dp)
                                .clickable {
                                    HomeEvents.GroupInfoPage.onHistoryWordClick(it)
                                }
                        )
                    }
                }
            }
        }
    }
}
@Composable
fun Title(txt:String,click:(()->Unit)?=null){
    var more = when(txt){
        "WordList" -> {
            var rt = "(${BookConf.words.size})"
            val cname = BookConf.instance.chapterName
            if(cname.startsWith("Top")){
                rt=LevelViewModel.getTopInfo(cname)
            }
            rt
        }
        else -> {
            if(txt.startsWith("Top")){
                LevelViewModel.getTopInfo(txt)
            }else{
                ""
            }
        }
    }

    Row(modifier = Modifier
        .padding(end = 16.dp)
    ){
        Text(mt(txt)+more, fontSize = 18.sp,color= MaterialTheme.colorScheme.onSurface, modifier = Modifier
            .clickable {
                if(click!=null) click()
            }
        )
    }
}